package cn.tq.pethome.dept.controller;

import cn.tq.pethome.bean.AjaxResult;
import cn.tq.pethome.bean.ResultBean;
import cn.tq.pethome.dept.domain.Department;
import cn.tq.pethome.dept.query.DepartmentQuery;
import cn.tq.pethome.dept.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询单个数据
     * @param id
     * @return
     */
    @ApiOperation(value = "通过ID查询部门" )
    @GetMapping(value = "/{id}")
    public Department selectDepartment(@PathVariable("id") @ApiParam(name="id属性",required = true)Long id){
        return departmentService.findById(id);
    }

    /**
     * 高级查询
     * @param query
     * @return
     */
    @ApiOperation(value = "高级查询所有部门" )
    @PostMapping
    public ResultBean<Department> queryDepartment(@RequestBody DepartmentQuery query){
        return departmentService.queryAll(query);
    }

    /**
     * 删除数据
     * @param id
     */
    @ApiOperation(value = "通过ID删除部门" )
    @DeleteMapping(value = "/{id}")
    public AjaxResult delDepartment(@PathVariable("id")Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除部门")
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            departmentService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 添加或修改数据
     * @param department
     * @return
     */
    @ApiOperation(value = "添加或修改部门" )
    @PutMapping
    public AjaxResult add0rUpDepartment(@RequestBody Department department){
        try {
            if (department.getId()!=null){
                departmentService.update(department);
            } else {
                departmentService.insert(department);
            }
            return AjaxResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 返回部门树关系
     * @return
     */
    @GetMapping
    @ApiOperation(value = "获取部门树关系结构")
    public List<Department> deptTrees(){
        return departmentService.getTree();
    }
}
